import axios from 'axios'
import router from "@/router";
import {serverIp} from "../../public/config";

const request = axios.create({
    baseURL: `https://${serverIp}:443`,
    timeout: 30000
})

var that = request;

// request 拦截器
// 可以自请求发送前对请求做一些处理
// 比如统一加token，对请求参数统一加密
request.interceptors.request.use(config => {
    config.headers['Content-Type'] = 'application/json;charset=utf-8';
    let access_token = localStorage.getItem("access_token") ? localStorage.getItem("access_token") : null
    if (access_token) {
        config.headers['Authorization'] = access_token;  // 设置请求头
    }

    return config
}, error => {
    return Promise.reject(error)
});

// response 拦截器
// 可以在接口响应后统一处理结果
request.interceptors.response.use(
    response => {
        let res = response.data;
        // 如果是返回的文件
        if (response.config.responseType === 'blob') {
            return res
        }
        // 兼容服务端返回的字符串数据
        if (typeof res === 'string') {
            res = res ? JSON.parse(res) : res
        }
        // 当权限验证不通过的时候给出提示
        if (res.code == 401) {
            ElementUI.Message({
                message: res.msg,
                type: 'error'
            });
            router.push("/login")
        }
		
		if (res.code == 1004) {
		
			localStorage.removeItem("access_token");
			that({
				method: "post",
				url: "/oauth/token",
				params: {
					grant_type: 'refresh_token',
					client_id : 'pictureShare',
					client_secret : 'pictureShare',
					refresh_token : localStorage.getItem('refresh_token'),
				},
			}).then((res) => {
				
				if (res.code == 200) {
					console.log(response)
					localStorage.setItem('access_token', res.result.token_type + " " + res.result.access_token)
					localStorage.setItem('refresh_token', res.result.refresh_token)
				} else {
					localStorage.removeItem("refresh_token");
					localStorage.removeItem("user");
					router.push("/login")
				}
			});
		}
        return res;
    },
    error => {
        console.log('err' + error) // for debug
        return Promise.reject(error)
    }
)


export default request

